<template>
  <div class="cart">
      <p class="title">{{name}}的购物车</p>
      <div v-for="(item,index) in cartItems" :key="item.id" >
          <span>{{index+1}}</span>
          <span>{{item.name}}</span>
          <span>{{item.price}}</span>
          <span>{{item.number}}</span>
          <span>{{item.price * item.number}}</span>
          <span>
              <button @click="remove(item.id)">删除</button>
          </span>
      </div>
      <div>
          <span>{{total}}</span>
      </div>
  </div>
</template>

<script>
// 从 vue 模块中导入 ref 和 computed 函数
import { ref , computed } from 'vue' ;

export default {
    name: 'Cart' ,
    props: {
        name: {
            type: String,
            require: true 
        }
    },
    // 组合式API
    setup( props , context ){

        console.log( 'props : ' , props );
        console.log( 'context : ' , context );

        let items = [
            { id: 123 , name: '红烧肉' , price: 26 , number: 2 },
            { id: 321 , name: '回锅肉' , price: 25 , number: 4 },
            { id: 222 , name: '盐煎肉' , price: 28 , number: 2 }
        ]

        let cartItems = ref( items ); // { value: items }
        console.log( cartItems );

        // 计算属性
        let total = computed( ()=>{
            let array = cartItems.value ;
            let t = 0 ;
            array.forEach( item => t += item.price * item.number );
            return t ;
        });

        // 这里返回的数据可以在其它选项和模板中使用 
        return {
            cartItems ,
            total
        }
    },
    methods: {
        remove(id) {
            let index = this.cartItems.findIndex( item => item.id == id );
            if( index != -1 ) {
                console.log( `即将删除${index}处的元素` );
                this.cartItems.splice( index , 1 );
            }
        }
    },
    mounted(){
        console.log( this );
    }
}
</script>

<style scoped>
.cart {
    border: 1px solid #dedede ;
    margin: 15px ;
}

.cart .title {
    margin: 5px ;
    color: blue ;
}

.cart>div {
    display: flex ;
    border-bottom: 1px solid #dedede ;
}

.cart>div:last-child {
    border-bottom: none ;
}

.cart>div span {
    flex-basis: 150px;
}

.cart>div:last-child span {
    margin-left: 600px ;
}
</style>